// server/plugins/seo-js-tag-position/index.ts
export default defineNitroPlugin((nitroApp) => {
  nitroApp.hooks.hook('render:html', (html) => {
    const regex = /<script\s+type=["']module["'].*?>.*?<\/script>/

    const head = html.head[0]
    const bodyAppend = html.bodyAppend[0]
    const script = head.match(regex)

    if (script != null && script[0]) {
      let scriptStr = script[0]
      html.head[0] = head.replace(scriptStr, '')
      const hrefLink = scriptStr.replace(/.*src="(.*)".*/g, '$1')
      const deferScript = `<script type="text/javascript">
  document.addEventListener('DOMContentLoaded', (e) => {
    const scriptDom = document.createElement('script')
    scriptDom.type = 'module';
    scriptDom.setAttribute('crossorigin','1')
    scriptDom.src = '${hrefLink}';
    document.head.appendChild(scriptDom)
  })
</script>`
      html.bodyAppend[0] = bodyAppend + deferScript
    }
  })
})
